<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
		<meta name="viewport" content="initial-scale=1, maximum-scale=3, minimum-scale=1, user-scalable=no" />
		<title></title>
		<script type="text/javascript" src="../js/vue.min.js"></script>
		<script type="text/javascript" src="../js/vconsole.min.js"></script>
		<style>
			.mgt15{
				margin-top: 15px;
			}
			.imageBox{
				display: flex;
				flex-wrap: wrap;
			}
			.itemBox{
				position: relative;
				width: 80px;
				height: 80px;
				margin:0 8px 8px 0;
			}
			.itemDel{
				position: absolute;
				top: 0;
				right: 0;
				z-index: 9;
				color: red;
			}
			.itemImage{
				width: 80px;
				height: 80px;
				object-fit: cover;
			}
			.textarea{
				width: 100%;
				height: 200px;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<form action="">
				<div class="mgt15">
					<upload v-model="formData.file1"></upload>
				</div>
				<div class="mgt15">
					<upload max="3" v-model="formData.file2"></upload>
				</div>
				<div class="mgt15">
					<button type="button" @click="formSubmit">提交表单</button>
				</div>
				<div class="mgt15" v-if="formDataStr">
					<textarea class="textarea" v-model="formDataStr"></textarea>
				</div>
			</form>
		</div>
		<script type="text/javascript">
			var vConsole = new VConsole();
			//定义组件
			Vue.component('upload', {
				template: `
				<div>
					<div class="imageBox">
						<div class="itemBox" v-for="(item,index) in showImage">
							<button class="itemDel" type="button" @click="imageDel(index)">删除</button>
							<img class="itemImage" :src="item" />
						</div>
						<div class="itemBox" v-if="loading">上传中...</div>
					</div>
					<input v-if="visible" type="file" @change="fileChange" />
				</div>`,
				model: {
					prop: 'value',
					event: 'change'
				},
				props: {
					value: [String, Array], //指定value值的类型
					max: {
						type: Number,
						default: 1 //默认最多上传一张
					}
				},
				data() {
					return {
						tempValue: [],//暂存
						loading: false, //表示是否正在上传文件
					}
				},
				computed: {
					visible() {
						if (this.loading) {
							return false;
						}
						if (!this.value) {
							return true;
						}
						return this.value.length < this.max
					},
					/**
					 * 格式化图片路径
					 */
					showImage() {
						var tempValue = this.tempValue;
						//在这里进行类型的转换，解决 "1.jpg,2.jpg"
						var fttValue = [];
						for (var i = 0; i < tempValue.length; i++) {
							//一般数据库只是存放相对路径，给文件添加文件服务器前缀，这一步视情况而定
							fttValue.push("https://api.jiuwusan.cn" + tempValue[i]);
						}
						return fttValue;
					}
				},
				watch: {
					value: function(newVal, oldVal) {
						console.log("更新 ：");
						this.setInitValue(newVal);
					}
				},
				created: function() {
					console.log("创建 ：", this.value);
					this.setInitValue(this.value);
				},
				methods: {
					/**
					 * 监听input的变化，进行图片上传
					 * @param {Object} e
					 */
					fileChange(e) {
						var that = this;
						that.loading = true;
						upload(e.target.files, function(res) {
							that.loading = false;
							if (res.code == 200) {
								// var value = JSON.parse(JSON.stringify(that.value || []));
								that.tempValue.push(res.path);
								this.$emit('change', that.tempValue);
							}
						});
					},
					/**
					 * 对初始值进行格式化
					 * @param {Object} value
					 */
					setInitValue(value) {
						if (!value) {
							this.value = [];
							return;
						}
						//在这里进行类型的转换
						if (Object.prototype.toString.call(value) != '[object Array]') {
							value = value.split(",");
						}
						this.value = value;
						this.tempValue = value;
						this.$emit('change', this.value);
					},
					imageDel(index) {
						console.log("删除===",index);
						this.tempValue.splice(index, 1);
						this.$emit('change', this.tempValue);
					}
				}
			})
			// 创建实例
			var app = new Vue({
				el: '#app',
				data() {
					return {
						formData: {
							file1: "",
							file2: []
						},
						formDataStr:""
					}
				},
				computed: {},
				methods: {
					formSubmit() {
						console.log("提交了表单===", this.formData);
						this.formDataStr=JSON.stringify(this.formData);
					}
				}
			});

			/**
			 * 文件上传的方法
			 * @param {Object} files
			 * @param {Object} callback
			 */
			var upload = function(files, callback) {
				if (!files) {
					console.log("未选择文件");
					return;
				}

				var formData = new FormData();
				formData.append("file", files[0]);

				var xhr = new XMLHttpRequest();
				xhr.onreadystatechange = function() {
					if (xhr.readyState === 4 && xhr.status === 200) {
						var rsJson = xhr.responseText;
						if (callback != undefined && Object.prototype.toString.call(callback) === '[object Function]') {
							try {
								var parseJSON = JSON.parse(rsJson);
								callback(parseJSON);
							} catch (e) {
								// callback({
								// 	code: -99
								// });
							}

						}
					}
				};

				xhr.open("POST", "https://api.jiuwusan.cn/common/upload/img");
				xhr.send(formData);
			};
		</script>
	</body>
</html>
